package top.broncho.anpods.ui.widget

import androidx.annotation.CheckResult
import com.google.android.material.appbar.AppBarLayout
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import top.broncho.anpods.util.safeOffer

@CheckResult
@ExperimentalCoroutinesApi
fun AppBarLayout.onOffsetChanged(): Flow<Int> = callbackFlow<Int> {
    val listener =
        AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            safeOffer(verticalOffset)
        }
    addOnOffsetChangedListener(listener)
    awaitClose { removeOnOffsetChangedListener(listener) }
}.conflate()